#include "DxGraphics.h"

CGraphics::CGraphics()
{
	_d3d=NULL;
	_d3ddev=NULL;
	_backbuffer=NULL;

}
CGraphics::~CGraphics()
{
	_backbuffer->Release();
	_d3d->Release();
	_d3ddev->Release();
}
bool CGraphics::Init_Direct3D(HWND hwnd, int width, int height)
{
	//initialize Direct3D
	if(NULL==(_d3d=Direct3DCreate9(D3D_SDK_VERSION)))
	{
		MessageBox(hwnd,"Error Initialize Direct3D","Error",MB_OK);
		return false;
	}
	//set Direct3D presentation parameters
	D3DPRESENT_PARAMETERS d3dpp; 
	ZeroMemory(&d3dpp, sizeof(d3dpp));

	d3dpp.Windowed = TRUE;
	d3dpp.SwapEffect = D3DSWAPEFFECT_COPY;
	d3dpp.BackBufferFormat = D3DFMT_X8R8G8B8;
	d3dpp.BackBufferCount = 1;
	d3dpp.BackBufferWidth = width;
	d3dpp.BackBufferHeight = height;
	d3dpp.hDeviceWindow = hwnd;

	//create Direct3D device
	if(FAILED(_d3d->CreateDevice(	D3DADAPTER_DEFAULT,
		D3DDEVTYPE_HAL,
		hwnd,
		D3DCREATE_SOFTWARE_VERTEXPROCESSING,
		&d3dpp,
		&_d3ddev)))
	{
		MessageBox(hwnd, "Error creating Direct3D device", "Error", MB_OK);
		return false;
	}

	//clear the back buffer to black
	_d3ddev->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,0), 1.0f, 0);

	//create pointer to the back buffer
	_d3ddev->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &_backbuffer);

	return true;
}

LPDIRECT3DSURFACE9 CGraphics::LoadSurface(char *fileName, D3DCOLOR transColor)
{
	LPDIRECT3DSURFACE9 image=NULL;
	D3DXIMAGE_INFO info;
	HRESULT result;

	result=D3DXGetImageInfoFromFile(fileName,&info);
	if(result!=D3D_OK)
		return NULL;

	result =_d3ddev->CreateOffscreenPlainSurface(	info.Width,
		info.Height,
		D3DFMT_X8R8G8B8,//surface format
		D3DPOOL_DEFAULT,//memory pool to use
		&image,
		NULL);
	if(result!=D3D_OK)
		return NULL;

	result =D3DXLoadSurfaceFromFile(image,
		NULL,//destination palette
		NULL,//destination rectangle
		fileName,//source filename
		NULL,//source rectangle
		D3DX_DEFAULT,//controls how image is filtered
		0,//for transparency (0 for none)
		NULL);//source image info (usually NULL)

	//make sure file was loaded
	if (result != D3D_OK)
		return NULL;

	return image;
}

void CGraphics::BeginRender(HWND hwnd,LPDIRECT3DSURFACE9 background)
{
	if(_d3ddev==NULL)
		return;
	RECT rsource;
	rsource.top=rsource.left=0;
	rsource.right=rsource.left+WINDOW_WIDTH;
	rsource.bottom=rsource.top+WINDOW_HEIGHT;
	_d3ddev->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(10,0,0), 1.0f, 0);
	if (!_d3ddev->BeginScene())
	{
		_d3ddev->StretchRect(background,NULL,_backbuffer,&rsource,D3DTEXF_NONE);
	}
}
void CGraphics::EndRender()
{
	_d3ddev->EndScene();
	_d3ddev->Present(NULL,NULL,NULL,NULL);

}